﻿local _G = _G
local addon, ns = ...
local cfg = {}
local profile = ns.profile
local LabelUI = CreateFrame("Frame") 
LabelUI.Init = {}
local function load(a1, a2, arg1)
	if a2 == "PLAYER_LOGIN" then
		local all, cur, profload
		all = {}
		if LabelUIcfg == nil then
			LabelUIcfg = {}
			for i,v in pairs(profile) do
				if type(i) == "string" then
					--LabelUIcfg["profile"] = i
					--break
					if not cur then
						cur = i
					end
					tinsert(all, i)
				end
			end
		end
		if ( not LabelUIcfg["profile"] or LabelUIcfg["profile"] and not profile[LabelUIcfg["profile"]] ) and not cur then
			for i,v in pairs(profile) do
				if type(i) == "string" then
					--LabelUIcfg["profile"] = i
					--break
					if not cur then
						cur = i
					end
					tinsert(all, i)
				end
			end
		end 
		if cur then
			profload = cur
		else
			profload = LabelUIcfg["profile"]
		end
		cfgprofile = profile[profload]()
		for i,v in pairs(cfgprofile) do
			cfg[i] = v			
		end
		if not LabelUIcfg["SaveVars"] then
			LabelUIcfg["SaveVars"] = {}
		end
		--wipe profile table for save additional ram (in current config version we save only 60-80kB)
		--[[for i,v in pairs(profile) do
			if type(i) == "string" then
				profile[i] = {}
			end
		end	]]-- 	
  		
		LabelUI.InitConfig()
		
		for i,v in pairs(_G.LabelUI_mod) do
			v.InitMod(LabelUI, profload, cfg)			
		end
		
		for i,v in pairs(LabelUI.Init) do
			local retOK, ret1 = pcall(v.func)
			--v.func() --use for debug
			if not retOK then
				local func = geterrorhandler()
				func("|cff19ccb1LabelUI:|r can not load module \""..v.name.."\" \n"..ret1)
			end	
		end
		if cur then
			LabelUI.ProfileChanger(cur, all, LabelUIcfg)
		end
	end
end
LabelUI:RegisterEvent("PLAYER_LOGIN")
LabelUI:SetScript("OnEvent", function(this, event, ...)
	load(this, event, ...)
end)
if not _G.LabelUI_mod then
	_G.LabelUI_mod = {}	
end
ns.LabelUI = LabelUI
ns.cfg = cfg